import type { RouteRecordName, RouteRecordRaw } from "vue-router";
import { debounce } from "es-toolkit";
import { defineStore } from "pinia";
import { ref } from "vue";
import { constantMenus } from "@/router";
import { filterNoPermissionTree, formatFlatteningRoutes, routeRankAscending } from "@/router/utils";
import { buildHierarchyTree, getKeyListFromArray } from "@/utils/tools";

interface cacheType {
    mode: string;
    name?: RouteRecordName;
}

/** 权限相关信息 */
export const usePermissionStore = defineStore("permission", () => {
    /** 静态路由生成的菜单 */
    const staticMenus = ref<RouteRecordRaw[]>(constantMenus);

    /** 整体路由（静态、动态）生成的菜单, 已前端过滤, 用于侧边栏菜单 */
    const wholeMenus = ref<RouteRecordRaw[]>([]);

    /**
     * 整体路由（一维数组格式）, 未做前端过滤
     * 注意: 这里后端只返回了当前用户角色的路由, 并不是系统中的所有路由
     */
    const flatteningRoutes = ref<RouteRecordRaw[]>([]);

    /** 缓存页面keepAlive */
    const cachePageList = ref<RouteRecordName[]>([]);

    /** 组装整体路由生成的菜单, 已根据权限过滤 */
    const setWholeMenus = (asyncRoutes: RouteRecordRaw[]): void => {
        const allRoutes = constantMenus.concat(asyncRoutes); // 返回新数组, 注意这里没有被拍平
        wholeMenus.value = filterNoPermissionTree((routeRankAscending(allRoutes)));
    };

    /** 设置拍平后的路由, 未根据权限过滤 */
    const setFlatteningRoutes = (asyncRoutes: RouteRecordRaw[]): void => {
        const allRoutes = constantMenus.concat(asyncRoutes); // 返回新数组, 注意这里没有被拍平
        flatteningRoutes.value = formatFlatteningRoutes( // 排序后拍平
            routeRankAscending(buildHierarchyTree(allRoutes, "meta")),
        );
    };

    /** 路由缓存处理 */
    const cacheOperate = ({ mode, name }: cacheType): void => {
        if (mode === "refresh") { // 刷新时清空除当前外的缓存页面
            cachePageList.value = cachePageList.value.filter(v => v !== name);
        } else if (mode === "add") { // 添加缓存页面
            cachePageList.value.push(name);
        } else if (mode === "delete") { // 删除缓存页面
            const delIndex = cachePageList.value.findIndex(v => v === name);
            delIndex !== -1 && cachePageList.value.splice(delIndex, 1);
        }
        /** 监听缓存页面是否存在于标签页，不存在则删除 */
        debounce(() => {
            let cacheLength = cachePageList.value.length;
            // TODO [] 替换标签页数组
            const multiTagsNameList = getKeyListFromArray([], "name");
            while (cacheLength > 0) {
                const lastCachePage = cachePageList.value[cacheLength - 1];
                if (multiTagsNameList.findIndex(v => v === lastCachePage) === -1) { // 缓存的路由在标签页中不存在
                    cachePageList.value.splice(cacheLength - 1, 1);
                }
                cacheLength--;
            }
        }, 100)();
    };

    /** 清空缓存页面 */
    const clearAllCachePage = (): void => {
        wholeMenus.value = [];
        cachePageList.value = [];
    };

    /** 按钮权限 */
    const permissions = ref<Array<string>>([]);

    /** 设置按钮权限 */
    const setPermissions = (value: Array<string>): void => {
        permissions.value = value;
    };

    /** 清空按钮权限 */
    const clearPermissions = (): void => {
        permissions.value = [];
    };

    return {
        staticMenus,
        wholeMenus,
        flatteningRoutes,
        cachePageList,
        setWholeMenus,
        cacheOperate,
        clearAllCachePage,
        setFlatteningRoutes,
        permissions,
        setPermissions,
        clearPermissions,
    };
});
